package cn.hxzy.kaoshi.controller;


import cn.hxzy.common.response.R;
import cn.hxzy.common.response.StatusEnum;
import cn.hxzy.kaoshi.entity.SysExamError;
import cn.hxzy.kaoshi.entity.SysSimulatedExam;
import cn.hxzy.kaoshi.mapper.SysExamErrorMapper;
import cn.hxzy.kaoshi.service.ISysExamErrorService;
import cn.hxzy.kaoshi.service.impl.SysExamErrorServiceImpl;
import cn.hxzy.kaoshi.service.impl.SysSimulatedExamServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 模拟考试 前端控制器
 * </p>
 *
 * @author tyqw
 * @since 2024-12-13
 */
@RestController
@RequestMapping("/sysSimulatedExam")
public class SysSimulatedExamController {
    @Autowired
    private SysSimulatedExamServiceImpl sysSimulatedExamService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SysExamErrorMapper sysExamErrorService;
    @Autowired
    private SysExamErrorMapper sysExamErrorMapper; // 注入 Mapper
    /**
     * 获取模拟考试题目
     * 本方法从sysSimulatedExamService中随机获取单选题、多选题和判断题，并将它们整合到一个列表中返回
     * 这样做是为了提供一个接口，用于获取混合类型的模拟考试题目，以便用户可以进行综合测试
     * map 参数用于传递一些查询条件，如用户ID、考试类型等
     * subjectMajor:模拟考类型
     * subjectLv:模拟考难度
     * @return 包含各种类型题目的列表
     */
    @RequestMapping("/getSimulatedExam")
    public R getSimulatedExam(@RequestBody Map<String, Object> map) {
        // 生成缓存键
        String cacheKey = "simulatedExam:" + map.toString();

        // 尝试从缓存中获取数据
        Map<String, Object> cachedData = (Map<String, Object>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedData != null) {
            // 获取缓存键的剩余过期时间
            Long expireTime = redisTemplate.getExpire(cacheKey, TimeUnit.SECONDS);
            cachedData.put("time",expireTime);
            cachedData.put("key",cacheKey);
            return R.success(cachedData);
        }





        // 初始化一个列表，用于存储所有类型的题目
        Map<String, Object> data = new HashMap<>();
        // 将随机单选题添加到题目列表中
        data.put("singleChoice", sysSimulatedExamService.getRandomSingleChoiceQuestions(map));
        // 将随机多选题添加到题目列表中
        data.put("multipleChoice", sysSimulatedExamService.getRandomMultipleChoiceQuestions(map));
        // 将随机判断题添加到题目列表中
        data.put("trueFalse", sysSimulatedExamService.getRandomTrueFalseQuestions(map));
        data.put("time",1800);
        data.put("key",cacheKey);
        // 将数据存入缓存，设置过期时间为30分钟
        redisTemplate.opsForValue().set(cacheKey, data, 30, TimeUnit.MINUTES);

        // 返回整合了所有题目的列表
        return R.success(data);
    }

    // 添加模拟考试记录
    @PostMapping("/add")
    public R add(@RequestBody Map map){
        SysSimulatedExam sisSimulatedExam =new SysSimulatedExam();
        sisSimulatedExam.setAnswerContent(map.get("answerContent").toString());
        sisSimulatedExam.setScore(map.get("score").toString());
        sisSimulatedExam.setUserId(Long.parseLong(map.get("userId").toString()));
        sisSimulatedExam.setSimulatedExamTime(LocalDateTime.now());
        sisSimulatedExam.setTimeUsed(map.get("timeUsed").toString());
        sisSimulatedExam.setErrorMessage(map.get("errorMessage").toString());
        SysExamError sysExamError =new SysExamError();
        sysExamError.setUserId(Long.parseLong(map.get("userId").toString()));
        List<Integer> errorQuestionIds = (List<Integer>) map.get("errorIds");
        for (Integer subjectId : errorQuestionIds) {
            sysExamError.setSubjectId(subjectId);
            sysExamErrorService.insertOrUpdate(sysExamError);
        }
        sysSimulatedExamService.add(sisSimulatedExam);
        redisTemplate.delete(map.get("key").toString());
        return R.success("添加成功");
    }
    //根据用户id查询模拟考试记录
    @GetMapping("/findByUserId/{userId}")
    public R findByUserId(@PathVariable("userId") Long userId){
        List<cn.hxzy.kaoshi.entity.SysSimulatedExam> list=sysSimulatedExamService.findByUserId(userId);
        return R.success(list);
    }
    @GetMapping("/kaoshijilu2/{userid}")
    public R findAllExamResults2(@PathVariable("userid") Long userid) {
        List<Map> list = sysSimulatedExamService.findAllExamResults2(userid);
        return R.success(list);
    }
    //根据id删除模拟成绩
    @GetMapping("/delejilu/{lid}")
    public R delejilu(@PathVariable("lid") Long id){
        Integer i=sysSimulatedExamService.deleteById(id);
        if(i>0){
            return R.success(true);
        }else {
            return R.success(false);
        }
    }

    /**
     * 根据考试ID查询所有问题
     * 此方法通过GET请求接收考试ID作为路径变量，然后调用服务方法获取该考试的所有问题
     * 它还处理考试数据，以便以易于消费的格式返回给客户端
     * 如果在处理请求时遇到任何问题，它会捕获异常并返回相应的错误信息
     *
     * @param examId 考试的唯一标识符，用于检索特定考试的问题
     * @return 返回一个R对象，其中包含成功时处理过的考试数据或错误时的错误信息
     */
    @GetMapping("/findAllQuestions/{examId}")
    public R findAllQuestions(@PathVariable("examId") Integer examId) {
        try {
            // 根据考试ID获取所有问题
            List<Map<String, Object>> allQuestions = sysSimulatedExamService.findAllQuestions(examId);
            // 处理考试数据以进行进一步的格式化或计算
            Map<String, Object> processedData = sysSimulatedExamService.processExamData(allQuestions);
            // 成功时返回处理过的数据
            return R.success(processedData);
        } catch (IllegalArgumentException e) {
            // 捕获非法参数异常并返回错误信息
            return R.error(StatusEnum.valueOf("参数错误: " + e.getMessage()));
        } catch (Exception e) {
            // 捕获其他异常并返回通用错误信息
            return R.error(StatusEnum.valueOf("查询考试科目信息失败: " + e.getMessage()));
        }
    }
@GetMapping("/findexaminationById/{id}")
    public R findexaminationById(@PathVariable Integer id) {
        Map<String, Object> examinationById = sysSimulatedExamService.findexaminationById(id);
        return R.success(examinationById);
    }

    @PostMapping("/submit")
    public R submitExam(@RequestBody Map<String, Object> examData) {
        sysSimulatedExamService.insertSimulatedExam(examData);
        return R.success("提交成功");
    }
        @GetMapping("/countdown")
    public R getCountdown() {
        try {
            // 固定返回 2小时
            String fixedTime = "02:00:00";

            // 构建响应
            Map<String, String> response = new HashMap<>();
            response.put("countdown", fixedTime);

            // 打印日志查看固定倒计时
            System.out.println("倒计时固定为：" + fixedTime);

            return R.success(response);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈
            return R.error(400,"服务器错误，无法获取倒计时");
        }
    }
    @GetMapping("/getErrorSubjcet/{userId}")
    public R getErrorSubjcet(@PathVariable("userId") Long userId) {
        List<SysExamError> list = sysExamErrorService.findAllByUserId(userId);

        // 创建一个列表来存储错误题目信息
        List<Map<String, Object>> errorSubjectDetails = new ArrayList<>();

        for (SysExamError sysExamError : list) {
            Integer subjectId = sysExamError.getSubjectId();
            Map<String, Object> errorSubject = sysExamErrorMapper.findErrorSubjcet(subjectId);
            if (errorSubject != null) {
                errorSubject.put("ordinalNumber", sysExamError.getOrdinalNumber());
                errorSubjectDetails.add(errorSubject);
            }
        }
        return R.success(errorSubjectDetails);
    }


}
